﻿using Ldt.CommonCapacitySupport.Business.Model;
using Ldt.SettingCenter.Core;
using LDT.CoreLibrary;
using LdtDataEngin.ModuleDetail.OptimizationModule.EvidenceDerivation;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;

namespace Ldt.CommonCapacitySupport.Controllers
{
    /// <summary>
    /// 推理能力提供
    /// </summary>
    public class InferentialCapacityController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        
        public static IConfiguration _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
        private static ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
        IConfigRetrieval configRetrieval;

        public InferentialCapacityController(ISettingCenter settingCenter)
        {
            configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter);
        }

        /// <summary>
        /// 执行设定
        /// </summary>
        /// <param name="outrelatid">唯一ID</param>
        /// <param name="typename">类型名称</param>
        private  void SetTaskDataInfo(string outrelatid, string typename)
        {
            //将日志放入同步数据的文件夹下
            System.Runtime.CallContext.SetData("baseDirectory", configRetrieval.GetLogPath());
            System.Runtime.CallContext.SetData("typename", typename.ToLower());
            System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_commoncapacitysupport);
            System.Runtime.CallContext.SetData("identifier", outrelatid.ToLower());
            System.Runtime.CallContext.SetData("customid", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());//当前标识ID
        }
        /// <summary>
        /// 证据要素与事实要素对应关系
        /// </summary>
        /// <param name="evidenceEelementModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("EvidenceElement")]
        public ReturnMessageModel EvidenceElement([FromBody] EvidenceEelementModel evidenceEelementModel)
        {
            ReturnMessageModel returnMessageModel = new ReturnMessageModel();
            returnMessageModel.result = new Ldt.CommonCapacitySupport.Business.Model.Result();
           
            try
            {
                DataContext dataLayerStores = new DataContext(new DataLayerSysStores(),new DyData_Analysis(),null);
                dataLayerStores.DataLayerAns.CaseType = evidenceEelementModel.CaseType;
                dataLayerStores.DataLayerAns.CaseId = evidenceEelementModel.CaseOnlyID;
                dataLayerStores.DataLayerAns.AppId = evidenceEelementModel.SystemCode;
                GetSysCaseCause dalCause = new GetSysCaseCause();
                dataLayerStores.DataLayerAns.CaseCausesList = new List<CaseCauseModel>();
                dataLayerStores.DataLayerAns.CaseCausesList.Add(dalCause.GetModelByCauseName(evidenceEelementModel.CauseID, evidenceEelementModel.CaseType));
                XmlDocument xmlEelement = new XmlDocument();
                xmlEelement.LoadXml(evidenceEelementModel.ElmentXml);
                List<RelationShip> relationShipsList = new List<RelationShip>();
                Dictionary<string, string> dicElement = new Dictionary<string, string>();
                dicElement.Add("fileFullName", @"config\optimizationCfg\caseCauseElementCfg\" + evidenceEelementModel.CaseType +
                    "_" + evidenceEelementModel.CauseID + ".xmlldt");
                string elementMessage = WebUtil.DoGet(configRetrieval.GetConnectionString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                if (elementcofig.result.code.ToString() == "1")
                {
                    string elementcofigstr = elementcofig.body;
                    OptimizeSourceSerializable optimizeSource = new OptimizeSourceSerializable();
                    dataLayerStores.DataLayerSys.optimizeFactConfig = optimizeSource.OptimizeCommonSourceContxt(elementcofigstr);
                }
                foreach (EvidenceMode evidencstr in evidenceEelementModel.EvidenceXMLList)
                {
                    dataLayerStores.DataLayerAns.SourceCode = evidencstr.DocID;
                    XmlDocument xmlEvidenc = new XmlDocument();
                    xmlEvidenc.LoadXml(evidencstr.EvidenceXML);
                    XmlNode root = xmlEvidenc.SelectSingleNode("//证据");
                    XmlDocument xml = new XmlDocument();
                    if (root != null)
                    {
                        xml.LoadXml(root.OuterXml);
                    }
                    else
                    {
                        xml = xmlEvidenc;
                    }
                    XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataLayerStores };
                    List<DataModel> dataModelsEvidencList = xmlUtilCommon.GetXMLByDataModelBackFill(xml).dataModelList;
                    List<DataModel> dataModelsEelementList = xmlUtilCommon.GetXMLByDataModelBackFill(xmlEelement).dataModelList;
                    EvidenceDerivationClass evidenceDerivationClass = new EvidenceDerivationClass(dataModelsEelementList, dataModelsEvidencList) { dataContext = dataLayerStores, IsXpath = "1" };
                    List<RelationShip> relationList = evidenceDerivationClass.Correspondence(dataLayerStores.DataLayerAns.CaseCausesList[0].CC_Name, "", evidenceEelementModel.CaseOnlyID, evidenceEelementModel.CaseType);
                    if (relationList.FirstOrDefault(a=> a.Type=="0")!=null)
                    {
                        relationShipsList.AddRange(relationList.Where(a=> a.Type=="0").ToList());
                    }
                  
                }

                returnMessageModel.result.code = "1";
                returnMessageModel.body = relationShipsList;
            }
            catch (Exception ex)
            {
                returnMessageModel.result.code = "0";

            }
            return returnMessageModel;
        }

    }
}
